package control;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

import data.PDMNode;
import data.PDMStructure;

/**
 * 
 * @author William Tran
 * 
 * Class to parse a pdm input file
 *
 */
public class PDMInputParser {
	
	
	/**
	 * Parse a pdmInputFile and use that data to initlialize a pdmStructure
	 * @param f - the file to be parsed
	 * @param pdmStructure - the pdmStructure to be initlialized
	 */
	public static void parsePDMInput(File f, PDMStructure pdmStructure ){
		
		Scanner input = null;
		try {
			input = new Scanner(new FileInputStream(f));
			
			String line;
			PDMNode pdmNode;
			while (input.hasNextLine()){
				
				//as we go through line by line, each line is a new task
				line = input.nextLine();
				pdmNode = new PDMNode();
				
				String lineInfo[] = line.split("\t");
				
				//first column is the task id which will also be the pdmNode key
				pdmNode.setNodeKey(lineInfo[0]);
				
				//second column is the duration of the task
				pdmNode.setDuration(Integer.parseInt(lineInfo[1]));
				
				//if length of lineInfo is 3 there there exist dependencies
				if (lineInfo.length == 3){
					
					//we will split by a comma i.e. B, C 
					String dependencies[] = lineInfo[2].split(",");
					
					//by this point those dependency nodes have already be added to the PDMStructure
					for (String s : dependencies){
						
						pdmNode.getDependancies().add(pdmStructure.getPdmNodes().get(s));
						
						//make sure we add dependents
						pdmStructure.getPdmNodes().get(s).getDependents().add(pdmNode);
					}
					
				}//lineInfo.length == 3
				
				pdmStructure.getPdmNodes().put(pdmNode.getNodeKey(),pdmNode);
				
			}//while input has next line
		
			
		} catch (FileNotFoundException e){
			e.printStackTrace();
		} finally {
			input.close();
		}
		
	}//end of parsePDMInput
}
